package com.quanyan.comment.client.impl;

import com.alibaba.dubbo.common.json.JSON;
import com.quanyan.comment.init.InvokeTargetInit;
import com.quanyan.comment.model.vo.MethodVo;
import com.quanyan.api.APIResponse;
import com.quanyan.comment.reqeust.APIRequest;
import com.quanyan.comment.serviceFacade.UserClient;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

import javax.validation.constraints.NotNull;

/**
 * @Author Hugo.Wwg
 * @Since 2016-05-03
 */
@Service("userClient")
public class UserClientImpl implements UserClient {

    public static final Logger log = LoggerFactory.getLogger(UserClientImpl.class);

    @NotNull
    @Override
    public APIResponse process(APIRequest request) {
        String command = request.getServicesName();
        MethodVo methodVo = InvokeTargetInit.invokeTargetMap.get(command);
        Object targetBean = methodVo.getTargetBean();
        Method targetMethod = methodVo.getTargetMethod();
        Class parameterType = targetMethod.getParameterTypes()[0];
        Object parameter = request.getRequestData();
        try {
            String params = JSON.json(parameter);
            Object realParam = JSON.parse(params, parameterType);
            APIResponse result = (APIResponse)targetMethod.invoke(targetBean, realParam);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage());
            return APIResponse.returnFail("调用失败");
        }
    }
}
